package com.zlp.demo.v1.controller;

import cn.hutool.core.convert.Convert;
import com.zlp.demo.v1.entity.UserInfo;
import com.zlp.demo.v1.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.CountDownLatch;


@RestController
public class UserController {

    @Autowired
    private UserService userService;

    // 并发数量=10000
    private static final Integer REQ_NUM = 100;
    // 上课点名人数
    private CountDownLatch countDown = new CountDownLatch(REQ_NUM);



    @GetMapping("getUserInfo")
    public UserInfo getUserInfo(Long userId) {

//        return userService.getUserInfo(userId);
//        return userService.getUserInfoFutureAsync(userId);//异步调用
        return userService.getUserInfoCompletableFuture(userId);//异步调用
    }

    @GetMapping("getUserBatchInfo")
    public UserInfo getUserBatchInfo(Long userId) {
        long start = System.currentTimeMillis();
        UserInfo userInfo = userService.getUserOrderBatch(userId);
//        System.out.println("查询结果："+userInfo.toString()+"耗时："+(System.currentTimeMillis()-start));
        return userInfo;
    }

    @GetMapping("getTestBatch")
    public void getTestBatch() {
        // 上课点名人数
        for (int i = 0; i < REQ_NUM; i++) {
            int finalI = i;
            new Thread(() -> {
                try {
                 /*   synchronized (countDown){
                        countDown.countDown();
                        countDown.wait();
                    }*/
                    UserInfo userInfo = userService.getUserOrderBatch(Convert.toLong(finalI));
                    System.out.println("查询结果："+userInfo.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();



    }
/*
    public static void main(String[] args) {
        // 上课点名人数
        CountDownLatch countDown = new CountDownLatch(REQ_NUM);
        for (int i = 0; i < REQ_NUM; i++) {
            int finalI = i;
            new Thread(() -> {
                try {
//                    countDown.countDown();
//                    countDown.wait();
                    RestTemplate restTemplate = new RestTemplate();
                    String url = "http://127.0.0.1:8010/getUserBatchInfo?userId=" + finalI;
                    ResponseEntity<UserInfo> exchange = restTemplate.exchange(url, HttpMethod.GET, null, UserInfo.class);
                    //System.out.println(exchange.getBody());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }
*/

    }
}
